package validator

import (
	"fmt"
	"github.com/gin-gonic/gin/binding"
	"github.com/go-playground/locales/zh"
	ut "github.com/go-playground/universal-translator"
	"github.com/go-playground/validator/v10"
	zh_translations "github.com/go-playground/validator/v10/translations/zh"
	"reflect"
)

var tsp *transP

type transP struct {
	trans ut.Translator
}

func initTrans() {
	tsp = &transP{}
}

func InitValidaotr() {
	initTrans()
	//设置转换器
	uni := ut.New(zh.New())
	trans, _ := uni.GetTranslator("zh")
	tsp.trans = trans
	// 绑定自定义验证器
	if v,ok := binding.Validator.Engine().(*validator.Validate); ok {
		// 注册翻译器
		_ = zh_translations.RegisterDefaultTranslations(v, trans)
		// 注册自定义验证函数
		_ = v.RegisterValidation("number", numbers)

		numbersMsg(v, trans)
	}
}

// 输出错误
func OutErrors(errs validator.ValidationErrors) map[string]string{
	return  errs.Translate(tsp.trans)
}

func numbers(fl validator.FieldLevel) bool {
	val := fl.Field().Int()
	fmt.Println(val)
	if val > 0 {
		return false
	}
	return true
}

func numbersMsg(v *validator.Validate, trans ut.Translator) {
	v.RegisterTagNameFunc(func(fld reflect.StructField) string {
		name:=fld.Tag.Get("label")
		return name
	})
	v.RegisterTranslation("number", trans, func(ut ut.Translator) error {
		return ut.Add("number", "{0}不能小于0!", true)
	}, func(ut ut.Translator, fe validator.FieldError) string {
		t, _ := ut.T("number", fe.Field(), fe.Field())
		return t
	})
}